package cn.bitkit.mybatis.criteria;

import cn.bitkit.mybatis.annotation.Query;
import cn.bitkit.mybatis.base.BaseCriteria;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author changbo
 */
@Slf4j
public class InCriteria implements BaseCriteria {

    @Override
    public String getSql(Query query, String fieldName, Object fieldValue, String column) {
        String value;
        if(fieldValue instanceof Collection<?> values){
            if(values.isEmpty()){
                return null;
            }
            if(values.size() > 1000){
                log.info("getSql:[in]value size:{}", values.size());
            }
            AtomicInteger index = new AtomicInteger(0);
            value = values.stream().map(e -> "#{" + fieldName + "[" + index.getAndIncrement() + "]}")
                    .collect(Collectors.joining(",", "(", ")"));
        }else{
            value = "( #{" + fieldName + "} )";
        }
        return column + " in " + value;
    }

}
